package com.hongkuncheng.cms.controller.admin;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.stereotype.Controller;
import com.hongkuncheng.cms.controller.BaseController;
import com.hongkuncheng.cms.helper.DataHelper;
import com.hongkuncheng.cms.helper.DateHelper;
import com.hongkuncheng.cms.model.Systemlog;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 系统操作日志
 *
 * @author 洪坤成
 */
@Controller
@Transactional
@RequestMapping("admin/systemlog")
public class AsystemlogController extends BaseController {

    // 日志列表
    @RequestMapping
    public String index() {
        checkAdminPermission("yunwei_systemsetup_systemlog");
        Criteria criteriaSystemlog = factorySession.createCriteria(Systemlog.class);
        StringBuilder callbackparams = new StringBuilder();
        String dt1 = request.getParameter("dt1") == null ? "" : request.getParameter("dt1");
        if (!dt1.isEmpty()) {
            Date date1 = DateHelper.convertToDatetime(dt1);
            criteriaSystemlog.add(Restrictions.ge("operationtime", date1));
            request.setAttribute("dt1", date1);
            callbackparams.append("&dt1=" + dt1);
        }
        String dt2 = request.getParameter("dt2") == null ? "" : request.getParameter
                ("dt2");
        if (!dt2.isEmpty()) {
            Date date2 = DateHelper.convertToDatetime(dt2);
            criteriaSystemlog.add(Restrictions.le("operationtime", date2));
            request.setAttribute("dt2", date2);
            callbackparams.append("&dt2=" + dt2);
        }
        if (callbackparams.length() > 0) callbackparams.deleteCharAt(0);
        request.setAttribute("callbackparams", callbackparams);
        int pageIndex = request.getParameter("pageindex") == null || request.getParameter("callbackparams") != null &&
                !callbackparams.toString().equals(request.getParameter("callbackparams")) ? 1 :
                Integer.parseInt(request.getParameter("pageindex"));
        int datasize = getDataSize();
        List<Systemlog> systemlogs = criteriaSystemlog.addOrder(Order.desc("operationtime"))
                .setFirstResult((pageIndex - 1) * datasize).setMaxResults(datasize).list();
        request.setAttribute("systemlogs", systemlogs);
        request.setAttribute("pageindex", pageIndex);
        int recordcount = systemlogs.size() == 0 ? 0 :
                Integer.parseInt(criteriaSystemlog.setProjection(Projections.countDistinct("id"))
                        .setFirstResult(0).uniqueResult().toString());
        request.setAttribute("recordcount", recordcount);
        int pagecount = DataHelper.calcPageCount(recordcount, datasize);
        request.setAttribute("pagecount", pagecount);
        return view();
    }

}
